package cn.edu.ecut.synchronize;

/**
 */
public class SynchronizationTest4 {

	public static void main(String[] args) {
		
		class Account { // 局部内部类
			long balance ; // 账户余额 (精确到圆)
			Account( long balance ){
				this.balance = balance ;
			}
		}
		
		// 创建一个 Account 实例，充当多个线程竞争的资源
		Account account = new Account( 1000 );
		
		Runnable deposit = new Runnable() {
			@Override
			public void run() {
				for( int i = 0 ; i < 5 ; i++ ) {
					synchronized ( account ) {
						if( account.balance == 0 ) {
							System.out.println( Thread.currentThread().getName() + "存款前的余额: " + account.balance );
							account.balance = account.balance + 1000 ;
							System.out.println( Thread.currentThread().getName() + "存钱后的余额: " + account.balance );
						} else {
							System.out.println( Thread.currentThread().getName() + "发现账户上还有钱，所以就暂时不存了。( " + account.balance + ")");
						}
					}
				}
			}
		};
		
		Runnable draw = new Runnable() {
			@Override
			public void run() {
				for( int i = 0 ; i < 10 ; i++ ) {
					synchronized ( account ) {
						if( account.balance > 0 ) {
							System.out.println( Thread.currentThread().getName() + "取款前的余额: " + account.balance );
							account.balance = account.balance - 1000 ;
							System.out.println( Thread.currentThread().getName() + "取款后的余额: " + account.balance );
						} else {
							System.out.println( Thread.currentThread().getName() + "发现账户没有有钱，所以就暂时不取了。" );
						}
					}
				}
			}
		};
		
		Thread t1 = new Thread( deposit , "张三丰" );
		Thread t2 = new Thread( deposit , "谢逊" );
		Thread t3 = new Thread( draw , "张无忌" );
		
		t1.start();
		t2.start();
		t3.start();

	}

}
